﻿using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace UFrame
{
    [CustomEditor(typeof(PrefabBinder))]
    public class PrefabBinderInspector : Editor
    {
        public override void OnInspectorGUI()
        {
            EditorGUI.BeginChangeCheck();

            var binder = target as PrefabBinder;

            if (binder.BindingInfoList == null || binder.BindingInfoList.Count == 0)
            {
                if (GUILayout.Button("Add New Binding"))
                {
                    if (binder.BindingInfoList == null)
                    {
                        binder.BindingInfoList = new List<PrefabBinder.BindingInfo>();
                    }

                    Undo.RecordObject(target, "Add Binding");
                    binder.BindingInfoList.Add(new PrefabBinder.BindingInfo());
                }

            }
            else
            {
                for (var j = binder.BindingInfoList.Count - 1; j >= 0; j--)
                {
                    var bindingInfo = binder.BindingInfoList[j];
                    EditorGUILayout.Separator();
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField("Binding");
                    EditorGUILayout.Space();
                    if (GUILayout.Button("+"))
                    {
                        Undo.RecordObject(target, "Insert Binding");
                        binder.BindingInfoList.Insert(j, new PrefabBinder.BindingInfo());
                    }
                    if (GUILayout.Button("-"))
                    {

                        Undo.RecordObject(target, "Remove Binding");
                        binder.BindingInfoList.RemoveAt(j);
                    }
                    EditorGUILayout.EndHorizontal();

                    bindingInfo.Prefab = (GameObject)EditorGUILayout.ObjectField("Prefab:", bindingInfo.Prefab, typeof(GameObject), true);

                    bindingInfo.Parent = (Transform)EditorGUILayout.ObjectField("Parent:", bindingInfo.Parent, typeof(Transform), true);
                }
            }

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(target, "GUI Change Check");
            }
        }
    }
}
